/*********************************************************************************
 *      Copyright:  (C) 2023 iot23<11>
 *                  All rights reserved.
 *
 *       Filename:  pack_data.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(20/04/23)
 *         Author:  iot23 <11>
 *      ChangeLog:  1, Release initial version on "20/04/23 11:04:25"
 *                 
 ********************************************************************************/

#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include "get_time.h"
#include "ds18b20.h"
#include "pack_data.h"


int pack_data(packet_t *pack, char *buf, int size)
{
	snprintf(buf, size, "/%s/%s/%f", pack->devsn, pack->time, pack->temper);

	return 0;
}


int get_data(packet_t *pack)
{
	if(!pack)
	{
		return -1;
	}

	if( get_temp(&pack->temper))
	{
		return -2;
	}
	get_time(pack->time, sizeof(pack->time));
			
	return 0;
}


int unpack_data(packet_t *pack, char *buf, int size)
{
	char	*buf_addr = NULL;
	char	*buf_start = NULL;
	char	*buf_end = NULL;
	char	 temp[8];
	
	buf_addr = strstr(buf,"/");
	buf_start = ++buf_addr;
	while( !(ispunct(*buf_addr)) )
	{
		buf_addr++;
	}
	buf_end = buf_addr;
	memset(pack->devsn, 0, sizeof(pack->devsn));
	memcpy(pack->devsn, buf_start, buf_end - buf_start);
	
	buf_end++;
	buf_addr = strstr(buf_end,"/");
	memset(pack->time, 0, sizeof(pack->time));
	memcpy(pack->time, buf_end, buf_addr - buf_end);

	buf_addr++;
	buf_end += strlen(buf) - strlen(pack->devsn);
	memset(temp, 0, sizeof(temp));
	memcpy(temp, buf_addr, buf_end - buf_addr);
	pack->temper = atof(temp);
}
